package com.htandroid.htandroid.tools;

import android.os.Handler;
import android.os.Message;

import com.htandroid.htandroid.sys.InstorageURL;

import org.ksoap2.transport.HttpTransportSE;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * 访问WebService的工具类,
 * <p/>
 * <p/>
 * Created by lkp on 2015/12/9.
 */

public class ToolSOAPxml {

    // 含有3个线程的线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(3);

    public static void callService(final String methodName, final String XMLString, final WebServiceCallBack webServiceCallBack) {
        callService(InstorageURL.SERVERURL, InstorageURL.NAME_SPACE, methodName, XMLString, webServiceCallBack);
    }

    /**
     * @param url                WebService服务器地址
     * @param namespace          命名空间
     * @param methodName         WebService的调用方法名
     * @param XMLString         WebService的xml数据
     * @param webServiceCallBack 返回结果回调接口
     */
    public static void callService(String url, final String namespace, final String methodName, final String XMLString, final WebServiceCallBack webServiceCallBack) {
        // 创建HttpTransportSE对象，传递WebService服务器地址
        //url="http://"+url+"/htwebservice/services/HT";//新版webservice地址
        ToolLog.log("---------call------------");
        url="http://"+url+ BaseUrl_New;//旧版webservice地址
        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            byte[] entity =  XMLString.getBytes();
            conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 用于子线程与主线程通信的Handler
        final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    webServiceCallBack.onSucced((String) msg.obj);
                } else {
                    webServiceCallBack.onFailure((String) msg.obj);
                }
            }
        };

        // 开启线程去访问WebService
        final HttpURLConnection finalConn = conn;
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                String result = null;
                Message mgs = mHandler.obtainMessage();
                try {
                    finalConn.getOutputStream().write(XMLString.getBytes());
                    if (finalConn.getResponseCode() == 200) {
                        // 获取服务器响应返回的SoapObject,//并把字节流转换成字符
                        result = convertStreamToString(finalConn.getInputStream());
                    }
                    mgs.what = 0;
                    mgs.obj = result;

                } catch (Exception e) {
                    mgs.what = 1;
                    mgs.obj = e.getMessage();
                }
                // 将获取的消息利用Handler发送到主线程
                mHandler.sendMessage(mgs);
            }
        });
    }

    /**
     * WebService回调接口
     */
    public interface WebServiceCallBack {

        void onSucced(String result);

        void onFailure(String result);
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}